package com.example.nfc.server;

import android.content.Context;
import android.text.TextUtils;

import com.example.nfc.server.network.http.HttpException;
import com.example.nfc.server.network.http.SyncHttpClient;
import com.example.nfc.server.utils.LogUtil;
import com.example.nfc.server.utils.NLog;
import com.example.nfc.server.utils.json.JsonMananger;

import org.apache.http.entity.StringEntity;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.List;

public class BaseAction {


    //public static final String DOMAIN = "http://192.168.2.100/admin";
    public static final String DOMAIN = "http://www.klmgzn.net.cn/admin";


    private final static String CONTENT_TYPE = "application/json";
    private final static String ENCODING = "utf-8";

    protected Context mContext;
    protected SyncHttpClient httpManager;
    /**
     * 构造方法
     *
     * @param context 上下文
     */
    public BaseAction(Context context) {
        this.mContext = context;
        httpManager = SyncHttpClient.getInstance(mContext);
    }

    /**
     * JSON转JAVA对象方法
     *
     * @param json json
     * @param cls  class
     * @throws HttpException
     */
    public <T> T jsonToBean(String json, Class<T> cls) throws HttpException {
        return JsonMananger.jsonToBean(json, cls);
    }

    /**
     * JSON转JAVA数组方法
     *
     * @param json json
     * @param cls  class
     * @throws HttpException
     */
    public <T> List<T> jsonToList(String json, Class<T> cls) throws HttpException {
        return JsonMananger.jsonToList(json, cls);
    }

    /**
     * JAVA对象转JSON方法
     *
     * @param obj object
     * @throws HttpException
     */
    public String BeanTojson(Object obj) throws HttpException {
        return JsonMananger.beanToJson(obj);
    }




    /**
     * POST请求
     * @param url
     * @param cla
     * @param obj
     * @param <T>
     * @return
     * @throws HttpException
     */
    public <T>T post( String url, Class<T> cla, Object obj) throws HttpException {
        url = new StringBuffer(DOMAIN).append("/").append(getURL(url,null)).toString() ;
        return postDo(url,cla,obj);
    }
    private <T>T postDo(String uri, Class<T> cla, Object obj) throws HttpException {
        String json = BeanTojson(obj);
        NLog.e("postDo",uri,json);
        StringEntity entity = null;
        try {
            entity = new StringEntity(json, ENCODING);
            entity.setContentType(CONTENT_TYPE);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String result = httpManager.post(mContext, uri, entity, CONTENT_TYPE);
        LogUtil.i(uri,result);
        if (!TextUtils.isEmpty(result)) {
            if(result.startsWith("{")&&cla!=null){
                return (T)JsonMananger.jsonToBean(result, cla);
            }else{
                return (T)result;
            }
        }
        return null;
    }

    /**
     * GET请求
     * @param url
     * @param cla
     * @param obj
     * @param <T>
     * @return
     * @throws HttpException
     */
    public <T>T get(String url, Class<T> cla, Object obj) throws HttpException {
        url = new StringBuffer(DOMAIN).append("/").append(getURL(url,obj)).toString() ;
        String result =  httpManager.get(mContext,url);
        if(Const.DEBUG) {
            // Log.e("getresult", url +"->"+ result);
        }
        if (!TextUtils.isEmpty(result)) {
            if(result.startsWith("{")&&cla!=null){
                return (T)JsonMananger.jsonToBean(result, cla);
            }else{
                return (T)result;
            }
        }
        return null;
    }

    /**
     * 获取完整URL属性值
     * @param url
     * @param obj
     * @return
     */
    protected static String getURL(String url, Object obj) {
        StringBuilder urlBuilder = new StringBuilder(url);
        if(obj!=null){
            urlBuilder.append("?");
            Class<?> cla = obj.getClass();
            Field[] fa =  cla.getDeclaredFields();;
            int i = 0 ;
            for(Field f:fa){
                f.setAccessible(true);

                try {
                    Object val = f.get(obj);
                    if(val!=null) {
                        String name = f.getName();
                        //_ -> [0]
                       //name = name.replaceAll("_", "[0]");
                        //$ -> .
                        //name = name.replaceAll("$", ".");
                        urlBuilder.append(name + "=" + val);
                        if (i < fa.length - 1) {
                            urlBuilder.append("&");
                        }
                    }
                }catch (Exception e){

                }
                i++;
            }
        }
        return urlBuilder.toString();
    }
}
